package com.glory.brepda.activity.lanjian.hdg;

import android.animation.ValueAnimator;
import android.content.res.ColorStateList;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.HdgLotRegisterQueryResEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 烘烤/抖动/过回流焊 烘烤入箱页面
 */
public class HdgBakeInRegisterActivity extends BaseActivity {

    @BindView(R.id.llMain)
    LinearLayout llMain;

    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;

    @BindView(R.id.etProductModule)
    FreeUI_ClearEditText etProductModule;

    @BindView(R.id.etMainMatType)
    FreeUI_ClearEditText etMainMatType;

    @BindView(R.id.etMainQty)
    FreeUI_ClearEditText etMainQty;

    @BindView(R.id.etOperator_ID)
    FreeUI_ClearEditText etOperator_ID;

    @BindView(R.id.etRegisterDate)
    FreeUI_ClearEditText etRegisterDate;

    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;

    @BindView(R.id.etBakeTemperature)
    FreeUI_ClearEditText etBakeTemperature;

    @BindView(R.id.etBakeDuration)
    FreeUI_ClearEditText etBakeDuration;

    @BindView(R.id.etBakeEqpId)
    FreeUI_ClearEditText etBakeEqpId;

    @BindView(R.id.btnAction)
    Button btnAction;

    private HdgLotRegisterQueryResEntity entity;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_hdg_bake_in_register;
    }

    @Override
    protected void initView() {
        // 初始化操作员 ，为操作用户
        etOperator_ID.setText(Constant.CURRENT_USER);
        setMainLayout(llMain);

        // 初始化日期 ，默认为当前时间
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String SEND_TIME = format.format(new Date());
        etRegisterDate.setText(SEND_TIME);

        initEdit(etLotID, sa -> {
            search();
        });

        // 初始化按钮颜色并监听批次输入变化，切换更顺滑
        updateActionButtonTint();
        etLotID.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateActionButtonTint();
            }

            @Override
            public void afterTextChanged(Editable s) { }
        });

    }

    @Override
    protected void initData() {
    }

    @OnClick({R.id.btnAction})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnAction:
                submit();
                break;
        }
    }
    private void btnClean1(){
        etLotID.setText(null);
        etProductModule.setText(null);
        etMainMatType.setText(null);
        etMainQty.setText(null);
        etComment.setText(null);
        etBakeTemperature.setText(null);
        etBakeDuration.setText(null);
        etBakeEqpId.setText(null);

        // 时间重设
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String SEND_TIME = format.format(new Date());
        etRegisterDate.setText(SEND_TIME);

        updateActionButtonTint();
    }

    // 提交
    private void submit(){
        if(getText(etLotID).equals("")){
            showToast("请先扫描批次信息", false);
            return;
        }
        if (!isNumeric(getText(etBakeTemperature))){
            showToast("烘烤温度输入不规范：应为整数或小数", false);
            return;
        }
        if (!isNumeric(getText(etBakeDuration))){
            showToast("烘烤时长输入不规范：应为整数或小数", false);
            return;
        }


        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showToast("批次登记成功", true);
                    btnClean1();
                    etLotID.requestFocus();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "HDG_LOT_REGISTER");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTION_TYPE", "BAKE_IN");
        map.addProperty("LOT_ID", getText(etLotID));
        map.addProperty("BAKE_IN_OPERATOR_ID", getText(etOperator_ID));
        map.addProperty("BAKE_IN_TIME", Objects.requireNonNull(etRegisterDate.getText(),"登记日期不能为空").toString());
        map.addProperty("BAKE_IN_COMMENT", getText(etComment));
        map.addProperty("BAKE_TEMPERATURE", Double.valueOf(getText(etBakeTemperature)));
        map.addProperty("BAKE_DURATION", Double.valueOf(getText(etBakeDuration)));
        map.addProperty("BAKE_EQP_ID", getText(etBakeEqpId));
        NetUtils.requestPostNet("IF.HDG_LOT_REGISTER", "Common", HdgBakeInRegisterActivity.this, map, callBack);
    }

    // 扫描批次
    private void search(){
        FreeUI_EntityCallBack<BaseResponseBean<HdgLotRegisterQueryResEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<HdgLotRegisterQueryResEntity>>
                (new TypeToken<BaseResponseBean<HdgLotRegisterQueryResEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<HdgLotRegisterQueryResEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    entity = response.body().getResponse().getBody();
                    inputValue(entity);
                    showToast("请求成功", true);
                    etLotID.requestFocus();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<HdgLotRegisterQueryResEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "请求失败");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("LOT_ID", getText(etLotID));
        map.addProperty("ACTION_TYPE", "QUERY");
        NetUtils.requestPostNet("IF.HDG_LOT_REGISTER", "Common", HdgBakeInRegisterActivity.this, map, callBack);
    }

    // ResponseEntity to value
    private void inputValue(HdgLotRegisterQueryResEntity entity){
        etLotID.setText(entity.getLOTID());
        etMainMatType.setText(entity.getMAINMATTYPE());
        etMainQty.setText(String.valueOf(entity.getMAINQTY()));
        etProductModule.setText(entity.getPRODUCTMODEL());
    }

    // 批次为空置灰，不为空恢复为主题蓝绿色，并使用动画过渡更流畅
    private void updateActionButtonTint() {
        String lot = getText(etLotID);
        boolean isEmpty = lot == null || lot.trim().isEmpty();
        int targetColor = ContextCompat.getColor(this,
                isEmpty ? R.color.free_ui_dark_gold_text_gray : R.color.free_ui_glory_theme_color);

        int currentColor = targetColor;
        if (btnAction.getBackgroundTintList() != null) {
            currentColor = btnAction.getBackgroundTintList().getDefaultColor();
        }

        if (currentColor != targetColor) {
            ValueAnimator colorAnimator = ValueAnimator.ofArgb(currentColor, targetColor);
            colorAnimator.setDuration(200);
            colorAnimator.addUpdateListener(anim -> {
                int c = (int) anim.getAnimatedValue();
                btnAction.setBackgroundTintList(ColorStateList.valueOf(c));
            });
            colorAnimator.start();
        } else {
            btnAction.setBackgroundTintList(ColorStateList.valueOf(targetColor));
        }

        float targetAlpha = isEmpty ? 0.6f : 1f;
        if (btnAction.getAlpha() != targetAlpha) {
            btnAction.animate().alpha(targetAlpha).setDuration(200).start();
        }
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("烤箱入箱");
        return new FreeUI_AddViewEntity("header", llMain);
    }

    // 判断是否为数字
    boolean isNumeric(String str) {
        if (str == null) return false;
        str = str.trim();
        return str.matches("^-?\\d+(\\.\\d+)?$");
    }

}